import json
from tools.read_pathlib import pic_path
import requests
from jsonpath import jsonpath
from loguru import logger
from tools.replace_var import replace_var
from tools.env_class import Env_Var
from tools.ex_var import exc_var

def requests_api(data):
    method = data["请求方法"]
    url = data["接口地址"]
    header = data["请求头"]
    param = data["请求参数"]
    header = replace_var(header)
    param = replace_var(param)
    # 反序列化操作：结合判空处理
    if header is not None:
        header = json.loads(header)
    if param is not None:
        param = json.loads(param)
    # 接口请求可能是get post put等各种请求方法，分支判断
    if method.lower() == "get":
        res = requests.request(method=method,url=url,params=param,headers=header)
    elif method.lower() == "post":
        # post请求：content-type的类型有关系，需要对每一种类型做处理，分支判断
        if header["Content-Type"] == "application/json":
            res = requests.request(method=method, url=url, json=param, headers=header)
        if header["Content-Type"] == "application/x-www-form-urlencoded":
            res = requests.request(method=method, url=url, data=param, headers=header)
        if header["Content-Type"] == "multipart/form-data":
            # 发送请求时候不能带上 "content-type":"multipart/form-data"
            header.pop("Content-Type") # 字典删除元素
            filename = param["filename"] # 文件名字的值
            obj_file = {"file":(filename,open(pic_path/filename,"rb"))}
            res = requests.request(method=method,url=url,headers=header,files=obj_file)

    elif method.lower() == "put":
        res = requests.request(method=method, url=url, json=param, headers=header)
    logger.info(res.text)
    exc_var(exc=data["提取响应字段"],resp=res)
    return res